package cn.gzmli.dtt.common.listener;


import cn.gzmli.dtt.common.config.cache.Config;
import cn.gzmli.dtt.common.entity.User;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {

//    public Logger logger = new Logger();

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        @SuppressWarnings("unused")
        HttpSession session = httpSessionBindingEvent.getSession();

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
        HttpSession session = event.getSession();
        System.out.println(session.getCreationTime());
        System.out.println(session.getLastAccessedTime());
        User curUser=(User)session.getAttribute("User");
        if(curUser!=null){
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.ms").format(new Date())+" 用户会话失效 id："+curUser.getId()
                    +" 用户："+curUser.getName());
        }

        //把当前销毁会话从用户会话缓存中移除
        if(Config.loginedUserSessions!=null){
        List<HttpSession> userSessions= Config.loginedUserSessions.get(curUser.getId());
        if(userSessions!=null){
            userSessions.remove(session);
            }
        }

    }


}

